﻿from rest_framework import serializers
from django.core.validators import FileExtensionValidator, get_available_image_extensions

class UploadImageSerializer(serializers.Serializer):
    # ImageField：检验上传的文件是否是图片
    image = serializers.ImageField(
        validators=[FileExtensionValidator(['jpg', 'jpeg', 'png', 'gif'])],
        error_messages={"required": "请上传图片！", "invalid_image": "请上传正确格式的图片！"}
    )

    def validate_image(self, value):
        # 图片大小单位是字节
        max_size = 10 * 1024 * 1024
        size = value.size
        if size > max_size:
            raise serializers.ValidationError("图片不能超过10MB！")
        return value